from abstractApi import AbstractModel
import numpy as np
import pandas as pd
import re
from .jzd_map import features
from .msk_jzd import predict as pred

# class FeatureDerive(AbstractModel):
class FeatureDerive():
    def __init__(self):
        return

    def loadParam(self, fileParam):
        """
        fileParam: dict<str, T> - defines the file names to read
        rtype: int
        """

        return

    def _derive(self, data):

        def var_func(k):
            v = data.get(k,'')
            if v == '':
                return np.nan
            else:
                return float(v)

        num_part = {k: var_func(k) for k in features}

        # 全部A01变量名需要映射时
        # num_data = {rename_dic[k]: v for k, v in num_part.items() if k in rename_dic.keys()}

        # 部分A01变量名需要映射时
        # num_data = {} 
        # for k, v in num_part.items():
        #     if k in rename_dic.keys():
        #         num_data[rename_dic[k]] =  v 
        #     else:
        #         num_data[k] =  v

        return{**num_part}

    def _predict(self, features):

        def prob_to_score(p,point0=45,PDO=-23):
            odds0 = 0.133
            B = PDO / np.log(2.0)
            A = point0 + B * np.log(odds0)

            score=np.around(A-B*np.log(p/(1-p)))
            score=max(0,score)
            score=min(100,score)

            return int(round(score,0))

        res = {}

        preds_prob = pred(features)

        res['lgb_score']  = str(prob_to_score(preds_prob))

        return res

    def _if_return(self, data):
        fr = re.compile(r'^flag_')
        flag_list = [i for i in data if fr.search(i)]
        data_temp = {key:values for key,values in data.items() if key in flag_list}

        if_return_value = 0
        for i in flag_list:
            try:
                if float(data_temp.get(i,0)) == 0 or float(data_temp.get(i,0)) == 1:
                    data_temp[i] = data_temp[i]
                else:
                    data_temp[i] = 0
            except:
                data_temp[i] = 0
            if_return_value += float(data_temp.get(i,0))
        
        return if_return_value

    def predict(self, param):
        """
        param: dict<str, T>
        rtype: dict<str, T>
        """
        # param={"brData":{"als_m12_id_nbank_avg_monnum": "1.25", "als_fst_id_nbank_inteday": "329", "als_m3_id_nbank_night_orgnum": "2", "als_m6_id_rel_orgnum": "",
        #                  "ald_id_nbank_orgnum": "", "flag_applyloanstr": "0", "flag_applyloan_d": "1"},"extraData":{"cus_num": "31543"},"inparam":{"cus_num": "31543"},"strategyType":"","pointType":"scoreconson","scoreData":"2","scoreBaseMealId":"","swiftNumber":"","scoreType":{"score":"scoreconson","api":"S7_0"},"apiCode":"4002497"}
        # param = {"brData":{"flag_applyloanstr": "1", "flag_graylistexpand": "0", "flag_multiplemodela": "1", "flag_populationderivation": "1", "gl_m1_beyond6_hit_months": "0", "gl_m1_max_list_level": "1", "pd_id_city_old_house_sort": ""},"extraData":{"cus_num": "10568"},"inparam":{"cus_num": "10568", "score": "774"},"strategyType":"","pointType":"scoremixbj","scoreData":"2","scoreBaseMealId":"","swiftNumber":"","scoreType":[{"score":"scoremixbj","api":"S1_0"}],"apiCode":"4002497"}

        data = param["brData"]
        # 添加客群参数
        param["inparam"]["cus_group"] = "cashon"

        if_return_value = self._if_return(data)
        res = {}
        features = self._derive(data)

        if if_return_value != 0:
            prob = self._predict(features)
            res['point']  = prob['lgb_score']   
        else:
            res['point'] = ''

        return res

####线下验证
fd = FeatureDerive()

df1 = pd.read_csv('test_3000_dts_result.csv', dtype=str , sep = ",",skiprows = [1])
df1 = df1.fillna('')
df = df1.to_dict('records')
#转为单条字典格式
result = []
for i in range(len(df)):
    data = df[i]
#        print(i)
    score = fd.predict(data)['point']
    if score != '':
        flag_score = 1
    else:
        flag_score = 0

    tmp = [data['cus_num'],
            flag_score,score]
    result.append(tmp)
header = ['cus_num',
          'flag_score','score']

result = pd.DataFrame(result,columns=header)
result.to_csv('线下3000样本打分结果.csv',index=False, encoding='utf-8')